# coding:utf-8
"""
Created on 2012-9-21

@author: fenceer
"""
import time
import json
import random
import datetime

import config
from common import tools


def ftime(timestamp, fmt='%Y-%m-%d %H:%M', short=False):
    timestamp = float(timestamp)

    if fmt == '%Y/%m/%d %H:%M':
        return time.strftime(fmt, time.localtime(timestamp))
    if not short:
        return time.strftime(fmt, time.localtime(timestamp))

    diff = (time.time() - timestamp)

    if diff < (60 * 1):
        fdate = '刚刚'
    elif diff < (60 * 60 * 1):
        fdate = str(int(diff // 60)) + '分钟前'
    elif diff < (60 * 60 * 24 * 1):
        fdate = str(int(diff // (60 * 60))) + '小时前'
    elif diff < (60 * 60 * 24 * 7):
        fdate = str(int(diff // (60 * 60 * 24))) + '天前'
    else:
        fdate = time.strftime(fmt, time.localtime(timestamp))

    return fdate


def ts2date(ts):
    date = time.localtime(ts)
    date = time.strftime('%Y-%m-%d', date)
    date = int(int(time.mktime(time.strptime(date, "%Y-%m-%d"))))
    return date


def media_time(times):
    return str(times // 60) + "分" + str(times % 60) + '秒'


def upfile(path='', fm=''):
    path = path if path.startswith('/') else '/' + path
    if path.startswith('http://') or path.startswith('https://'):
        return path + fm
    return config.srv['upyun']['domain'] + path + fm


def cutfile(url):
    return url.replace(config.srv['upyun']['domain'], '')


def age(birthday):
    aa = int(time.strftime('%Y', time.localtime(time.time()))) - int(time.strftime('%Y', time.localtime(birthday)))
    return aa


def hide_phone(phone):
    return phone[:3] + "*****" + phone[8:]


def remain(ts):
    current = time.time()
    deadline = ts + 7 * 24 * 60 * 60
    diff = deadline - current
    fdate = ''
    if diff < (60 * 1):
        fdate = '已过期'
    elif diff < (60 * 60 * 1):
        fdate = str(int(diff // 60)) + '分钟后过期'
    elif diff < (60 * 60 * 24 * 1):
        fdate = '离过期只有' + str(int(diff // (60 * 60))) + '小时'
    elif diff < (60 * 60 * 24 * 7):
        fdate = str(int(diff // (60 * 60 * 24))) + '天' + str(
            int((diff - 60 * 60 * 24 * int(diff // (60 * 60 * 24))) // 3600)) + '小时'
    return fdate


def left_time(seconds):
    seconds = int(seconds)
    days = seconds // 86400
    hour = (seconds - 86400 * days) // 3600
    return str(days) + '天' + str(hour) + '时'


def time_get(enroll_time, times, typ=1):
    if typ == 1:
        start = int(enroll_time) - 86400 * int(times)
        end = int(enroll_time)
        res = "{0}-{1}".format(tools.ts2str(start, fmt='%Y年%m月%d日'),
                               tools.ts2str(end, fmt='%m月%d日'))
    elif typ == 2:
        if times and enroll_time != times:
            res = "{0}-{1}".format(tools.ts2str(int(enroll_time), fmt='%Y/%m/%d'),
                                   tools.ts2str(int(times), fmt='%m/%d'))
        else:
            res = tools.ts2str(int(enroll_time), fmt='%Y/%m/%d')
    elif typ == 3:
        if times and enroll_time != times:
            res = "{0}-{1}".format(tools.ts2str(int(enroll_time), fmt='%Y年%m月%d日'),
                                   tools.ts2str(int(times), fmt='%m月%d日'))
        else:
            res = tools.ts2str(int(enroll_time), fmt='%Y年%m月%d日')
    else:
        res = ""

    return res


def ts2week(ts, typ=1):
    date = tools.ts2str(ts, '%Y-%m-%d')
    import datetime
    if typ == 1:
        week_day_dict = {0: '星期一', 1: '星期二', 2: '星期三', 3: '星期四', 4: '星期五', 5: '星期六', 6: '星期天'}
    elif typ == 2:
        week_day_dict = {0: 'MONDAY', 1: 'TUESDAY', 2: 'WEDNESDAY', 3: 'THURSDAY', 4: 'FRIDAY', 5: 'SATURDAY',
                         6: 'SUNDAY'}
    elif typ == 3:
        week_day_dict = {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday',
                         6: 'Sunday'}
    else:
        week_day_dict = {0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri', 5: 'Sat',
                         6: 'Sun'}
    date_list = date.split('-')
    any_day = datetime.datetime(int(date_list[0]), int(date_list[1]), int(date_list[2])).weekday()
    return week_day_dict[any_day]


def ts2month(ts):
    _month = tools.ts2str(ts, '%m')
    month_dict = {1: 'JAN',
                  2: 'FEB',
                  3: 'MAR',
                  4: 'APR',
                  5: 'MAY',
                  6: 'JUN',
                  7: 'JUL',
                  8: 'AUG',
                  9: 'SEP',
                  10: 'OCT',
                  11: 'NOV',
                  12: 'DEC'}
    return month_dict[int(_month)]


# 20170309月份->英文
def ts2enmonth(ts):
    _month = tools.ts2str(ts, '%m')
    month_dict = {1: 'JANUARY',
                  2: 'FEBRUARY',
                  3: 'MARCH',
                  4: 'APRIL',
                  5: 'MAY',
                  6: 'JUNE',
                  7: 'JULY',
                  8: 'AUGUST',
                  9: 'SEPTEMBER',
                  10: 'OCTOBER',
                  11: 'NOVEMBER',
                  12: 'DECEMBER'}
    return month_dict[int(_month)]


# 100 以内转中文数字
def num2chinese(num):
    num_dict = {0: '',
                1: '一',
                2: '二',
                3: '三',
                4: '四',
                5: '五',
                6: '六',
                7: '七',
                8: '八',
                9: '九',
                10: '十'}
    if int(num) < 11:
        return num_dict[int(num)]
    else:
        if int(num) // 10 != 1:
            return num_dict[int(num) // 10] + num_dict[10] + num_dict[int(num) % 10]
        else:
            return num_dict[10] + num_dict[int(num) % 10]


def add_http(url):
    path = url if url else ''
    if path.startswith('http://'):
        return path
    path = 'http://' + url
    return path


def random_qrcode(_list):
    return _list[random.randint(0, len(_list) - 1)]


def json_dump(_list):
    return json.dumps(_list)


def get_weekday():
    return ['一', '二', '三', ' 四', '五', '六', '日'][datetime.datetime.now().weekday()]


# 剩余时间统计
def count_down(ts, short=False):
    if short:
        if (ts // 3600) > 0:
            return str(ts // 3600) + '小时' + str((ts % 3600) // 60) + '分'
        else:
            return str((ts % 3600) // 60) + '分'
    else:
        return str(ts // 3600) + '时' + str((ts % 3600) // 60) + '分' + str(ts % 60) + '秒'


filters = {
    'ftime': ftime,
    'media_time': media_time,
    'upfile': upfile,
    'age': age,
    'hide_phone': hide_phone,
    'remain': remain,
    'left_time': left_time,
    'ts2week': ts2week,
    'add_http': add_http,
    'ts2month': ts2month,
    'num2chinese': num2chinese,
    "random_qrcode": random_qrcode,
    'json_dump': json_dump,
    'get_weekday': get_weekday,
    'ts2enmonth': ts2enmonth,
    'count_down': count_down,
}
